package de.kum.dhdroid;

import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;

public class ExamReminderService extends Service{

	private SQLiteDatabase dhDroidServiceDB;
	
	public int onStartCommand(Intent intent, int flags, int startId) {
        
		//Instanz der Datenbank wird geholt
		try {
			dhDroidServiceDB = getApplicationContext().openOrCreateDatabase("DHDroid", Context.MODE_PRIVATE, null);
		} catch (Exception e) {
		}
		
		//Tage die vorher Benachrichtigt werden sollen, werden geholt
		int daysBefore = getDaysBeforeRemind();
		
		//Klausurtermine werden geholt
		String[] examDays = getExamDays();
		
		//aktuelles Datum
		Calendar calendar = Calendar.getInstance();	
		
		//Uhrzeit der Benachrichtigung
		int remindHour = getRemindHour();
		
		if (remindHour == calendar.get(Calendar.HOUR_OF_DAY)) {
			boolean needNotification = false;
			int countExams = 0;
			
			//Alle Klarusurtermine werden durchlaufen und verglichen
			for (int i = 0; i < examDays.length; i++) {
				long dateDiff = getDateDiff(examDays[i], calendar);
				if (dateDiff >= 0) {
					if (dateDiff <= daysBefore) {
						needNotification = true;
						countExams++;
					}	
				}
			}
			
			if (needNotification) {
				createNotification(getApplicationContext(), calendar, countExams);
			}
		}
		
		try {
			dhDroidServiceDB.close();	
		} catch (Exception e) {
		}
        
        return Service.START_NOT_STICKY;
	}

	//Erzeugen der Benachrichtigung
	@SuppressWarnings("deprecation")
	private void createNotification(Context context, Calendar calendar, int countExams){
		
		Intent notifyIntent = new Intent(context, DHDroid.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0);
		
		NotificationManager notifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.ic_launcher, "anstehende Klausuren!", calendar.getTimeInMillis()); 
		
		String notificationText = countExams + " anstehende Klausur!";
		if (countExams > 1) {
			notificationText = countExams + " anstehende Klausuren!";	
		}
		notification.setLatestEventInfo(context, "DHDroid", notificationText, pendingIntent);		
		
		Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

		notification.sound = notificationSound;		
		notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
		
		notifyManager.notify(0 ,notification);
		
	}
	
	//Differnez der Tage wird berechnet
	private long getDateDiff(String dateString, Calendar currentTime){
		
		Calendar examDate = stringToDate(dateString);
		long days = examDate.getTimeInMillis() - currentTime.getTimeInMillis();
		days = days / (24*60*60*1000);
		
		return days;
	}
	
	//Umwandlung von Datums-String in Calendar-Format
	private Calendar stringToDate(String dateString){
		String[] dateParts = dateString.split("\\.");
		
		Calendar examDate = Calendar.getInstance();
		int month = Integer.parseInt(dateParts[1]);
		
		examDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateParts[0]));
		examDate.set(Calendar.MONTH, month - 1);
		examDate.set(Calendar.YEAR, Integer.parseInt(dateParts[2]));
		
		return examDate;
	}

	public IBinder onBind(Intent intent) {
		return null;
	}

	//siehe onStartCommand
	private int getDaysBeforeRemind(){
		Cursor c = dhDroidServiceDB.rawQuery("SELECT * FROM Settings WHERE ID = 1;", null);

		int daysBefore = 0;
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					daysBefore = c.getInt(5);
				} while (c.moveToNext());
			}
		}
		return daysBefore;
	}
	
	//siehe onStartCommand
	private int getRemindHour(){
		Cursor c = dhDroidServiceDB.rawQuery("SELECT * FROM Settings WHERE ID = 1;", null);

		int remindHour = 0;
		if (c != null) {
			if (c.moveToFirst()) {
				do {
					remindHour = c.getInt(6);
				} while (c.moveToNext());
			}
		}
		return remindHour;
	}
	
	//siehe onStartCommand
	private String[] getExamDays(){
		
		String condition = ("ORDER BY date(substr(Date,7)||substr(Date,4,2)||substr(Date,1,2)) ASC");
		Cursor examCursor = dhDroidServiceDB.rawQuery("SELECT * FROM 'Exam' " + condition + ";", null);

		String[] examDays = new String[examCursor.getCount()];
		
		int i = 0;
		if (examCursor != null) {
			if (examCursor.moveToFirst()) {
				do {
					examDays[i] = examCursor.getString(1);
					i++;
				} while (examCursor.moveToNext());
			}
		}

		return examDays;
	}

}
